


let cfg = require('./utils/cfg');

class ActionMgr{
    constructor(){
        this._actions = {}; // actionId:Action
        this._targetActions = {}; // targetId:Action
    }

    update(){
        let dt = cfg.gameApp.fps.dt;

        // 简单实现
        let actions = this._actions;
        let ids = Object.keys(actions);
        ids.forEach(id=>{
            let action = actions[id];
            if(!action.running){
                console.error(`action is not runing....`);
            }
            action.step(dt);

            // 删除所有已经结束的动画
            if(action.isDone()){
                this.removeAction(action);
            }
        });
    }

    addAction(action){

        if(!action.target){
            throw new Error(`action.target is null!`);
        }

        if(this._targetActions[action.target.id]){
            // 如果已经有了.  直接删除之前的action
            console.warn(`targetId:${action.target.id} already has action!`);
            this.removeAction(action);
        }
        this._actions[action.id] = action;
        this._targetActions[action.target.id] = action;
        action.start();
    }

    removeAction(action){
        if(!action){
            throw new Error('action is null!');
        }
        delete this._actions[action.id];
        delete this._targetActions[action.target.id];
        action.target = null;
    }

    removeAllActionOnTarget(target){
        let action = this._targetActions[target.id];
        if(action){
            this.removeAction(action);
        }
    }

    getActionByNode(nd){
        return this._targetActions[nd.id];
    }
}

module.exports = ActionMgr;
